package com.hl.wechat.demo.websocket;

import com.alibaba.fastjson.JSON;
import com.hl.wechat.demo.enums.MessageActionEnum;
import com.hl.wechat.demo.message.WebSocketMessageEntity;
import com.hl.wechat.demo.service.SpringContext;
import com.hl.wechat.demo.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import sun.misc.MessageUtils;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * WebSocket监听管理
 */
@ServerEndpoint("/chat/{id}")
@Component
public class WebSocketListener {
    private Logger logger = LoggerFactory.getLogger(WebSocketListener.class);
    static WebSocketManager webSocketManager;

    public WebSocketListener() {

    }

    /**
     * 客户端连接
     *
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "id") String userId) throws IOException {
        if (StringUtils.isEmptyString(userId)) {
            session.close();
            return;
        }
        if (webSocketManager == null) {
            webSocketManager = SpringContext.getBean(WebSocketManager.class);
        }
        webSocketManager.addUser(userId, session);
    }

    /**
     * 客户端关闭
     *
     * @param userId
     */
    @OnClose
    public void onClose(@PathParam(value = "id") String userId) {
        if (webSocketManager == null) {
            webSocketManager = SpringContext.getBean(WebSocketManager.class);
        }
        webSocketManager.remove(userId);
    }

    @OnMessage
    public void onMessage(@PathParam(value = "id") String userId,String messag){
        try {
            WebSocketMessageEntity webSocketMessageEntity = JSON.parseObject(messag, WebSocketMessageEntity.class);
            if (webSocketMessageEntity.getAction()==MessageActionEnum.FORWORD.getValue()){
                logger.info("转发{}------>{},msg",webSocketMessageEntity.getFromId(),webSocketMessageEntity.getToId(),webSocketMessageEntity.getMsg());
                new ActionHandler.MessageForwardHandler(webSocketManager,webSocketMessageEntity).doEvent();
            }
        }catch (Exception e){

        }



    }

}
